import React, { useState, useRef } from "react";
import axios from "axios";
import "./login.css";
import { useNavigate } from "react-router-dom";
import { Button, Form, Input } from "antd";

var base = {}


const Login = (props) => {
  const mobile = useRef("");
  const password = useRef("");
  const captcha = useRef("");
  const navite = useNavigate();
  const [form] = Form.useForm();
  const [getCap, setGetCap] = useState(true)
  const GetCaptcha = () => {
    axios.get("http://192.168.61.84:8000/user/v1/base/captche").
      then(function (res) {
        base = res.data
        setGetCap(!getCap)
        console.log(base)
      })
  }

  const onFinish = (values) => {
    console.log('Received values of form: ', values);
  };

  const handleLogin = () => {
    props.setIfLogin(true);
    console.log(form.getFieldsValue().mobile);

    axios.post("http://192.168.61.84:8000/user/v1/user/passwordlogin",
      {
        mobile: form.getFieldsValue().mobile,
        password: form.getFieldsValue().password,
        captcha: form.getFieldsValue().captcha,
        captcha_id: base.captchaid
      }).then(data => {
        console.log(data);
        if (data.data.code === 200) {
          alert("登录成功");
          localStorage.setItem("token", data.data.x_token);
          localStorage.setItem("id", data.data.id);
          localStorage.setItem("role", data.data.role);
          localStorage.setItem("username", data.data.username);
          localStorage.setItem("name", data.data.name);
          
          if (data.data.role === 2) {
            navite("/home")
          } else if (data.data.role === 3) {
            navite("/home");
          } else if (data.data.role === 1) {
            navite("/user");
          }
        } else {
          alert("账号或密码输入错误，请重新输入");
        }
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };

  const redirectToRegister = () => {
    navite("/register")
  };
  const redirectToFindPassword = () => {
    navite("/findPassword")
  }

  return (
    <div className="container">
      <div className="login-wrapper">
        <div className="header">欢 迎 登 录</div>
        <Form onFinish={onFinish} form={form}>
          <div className="form-wrapper">
            <Form.Item
              label="手机号"
              name="mobile"
              ref={mobile}
              rules={[
                {
                  required: true,
                  message: "手机号不能为空",
                }, {
                  pattern: /^\d{11}$/,
                  message: "请输入正确的手机号",
                },
              ]}
            >
              <Input/>
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              ref={password}
              rules={[
                {
                  required: true,
                  message: "密码不能为空",
                },
                {
                  min:6,
                  max: 10,
                  message: "密码长度必须在6到10位之间",
                },
                // {
                //   validator: (_, value) =>
                //     value && !/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,10}$/.test(value)
                //       ? Promise.reject(
                //         new Error('密码必须包含至少6个字符,一个字母和一个数字')
                //       )
                //       : Promise.resolve()
                // },
              ]}
            >
              <Input.Password/>
            </Form.Item>
            <Form.Item
              label="验证码"
              name="captcha"
              ref={captcha}
              rules={[
                {
                  required: true,
                  message: "验证码不能为空",
                },
              ]}
            >
              <Input/>
            </Form.Item>
            <img src={`${base.picCode}`} onClick={GetCaptcha}></img>
            <div className="btn">
              <Button type="primary"
                htmlType="submit"                
                onClick={handleLogin}>登录</Button>
            </div>
          </div>
        </Form>

        <div className="msg">
          没有账户?
          <a onClick={redirectToRegister}>点 击 注 册</a>
        </div>
        <div className="msg">
            忘记密码?
            <a onClick={redirectToFindPassword}>找 回 密 码</a>
          </div>
      </div>
    </div>
  );
};

export default Login;
